package main

import (
	"encoding/json"
	"fmt"
	"log"
	"mygoedu/day11/socket"
	"net"
	"strconv"
	"time"
)

func handelRequest(conn net.Conn) {
	log.Println("establish connect from: ", conn.RemoteAddr())
	conn.SetReadDeadline(time.Now().Add(30 * time.Second))
	defer conn.Close()
	for {
		requestBytes := make([]byte, 256)
		readLen, err := conn.Read(requestBytes)
		if err != nil {
			fmt.Println(err)
			break
		}

		var request socket.Request
		err = json.Unmarshal(requestBytes[0:readLen], &request)
		socket.CheckError(err)
		log.Printf("a=%d,b=%d client: %s\n", request.A, request.B, conn.RemoteAddr())

		sum := request.A + request.B
		response := socket.Response{Sum: sum}
		responseBytes, _ := json.Marshal(response)
		_, err = conn.Write(responseBytes)
		socket.CheckError(err)
	}
}

func main() {
	ip := "127.0.0.1"
	port := 8080
	addr, err := net.ResolveTCPAddr("tcp", ip+":"+strconv.Itoa(port))
	socket.CheckError(err)
	log.Println("listen", addr)

	listener, err := net.ListenTCP("tcp", addr)
	socket.CheckError(err)
	log.Println("waiting for client...")

	defer listener.Close()
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println(err)
			continue
		}
		go handelRequest(conn)

	}
}
